package com.groot.common.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * @decoration 统一编码拦截器
 * classpath:xin.spring.medical.common.filter.EnCodingFilter.java
 * @author spring
 * @date 2019-02-27 10:17:00
 */
@WebFilter(filterName="EnCodingFilter",urlPatterns="/*",
initParams={
		@WebInitParam(name="encoding", value="UTF-8"),
		@WebInitParam(name="contentType",value="Content-type"),
		@WebInitParam(name="contentValue",value="text/html;charset=UTF-8")
		})
public class EnCodingFilter implements Filter {

/**
 * 编码
 */
private String encoding;

/**
 * 浏览器解析类型
 */
private String contentType;

/**
 * 浏览器解析类型值
 */
private String contentValue;

/**
 * Log4j
 */
private static Logger LOGGER = Logger.getLogger(EnCodingFilter.class);

@Override
public void init(FilterConfig filterConfig) throws ServletException {
	encoding = filterConfig.getInitParameter("encoding");
	contentType = filterConfig.getInitParameter("contentType");
	contentValue = filterConfig.getInitParameter("contentValue");
	LOGGER.info("..EncodingFilter.." + encoding);
	LOGGER.info("..EncodingFilter.." + contentType);
	LOGGER.info("..EncodingFilter.." + contentValue);
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
		throws IOException, ServletException {
	HttpServletRequest request = (HttpServletRequest)req;
	HttpServletResponse response = (HttpServletResponse)res;
	request.setCharacterEncoding(encoding);
	response.setCharacterEncoding(encoding);
	response.setHeader(contentType, contentValue);
	response.setCharacterEncoding(encoding);
	LOGGER.info("do encoding Filter ==> " + encoding);
	chain.doFilter(request, response);
}

@Override
public void destroy() {
	LOGGER.info("EnCodingFilter is destroy()");
}

}
